package com.tanhua.server.service.impl;

import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.Settings;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.server.intercepter.UserThreadLocal;
import com.tanhua.server.service.SettingsService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

@Service
public class SettingsServiceImpl implements SettingsService {

    //settings
    @DubboReference
    private SettingsApi settingsApi;

    //注入远程问题业务层
    @DubboReference
    private QuestionApi questionApi;

    //通用设置-查询
    @Override
    public SettingsVo settings() {
        //创建一个返回实体类对象用来接收参数
        SettingsVo vo = new SettingsVo();
        //1.获取用户id
        Long userId = UserThreadLocal.getUserId();
        vo.setId(userId);

        //2.获取用户手机号
        String phone = UserThreadLocal.getPhone();
        vo.setPhone(phone);

        //3.获取用户的陌生人问题
        Question question = questionApi.findByUserId(userId);
        String txt = question == null ? "你喜欢java吗？" : question.getTxt();
        vo.setStrangerQuestion(txt);
        //4.获取用户app通知开关数据
        Settings settings = settingsApi.findByUserId(userId);
        if (settings != null) {
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
            vo.setLikeNotification(settings.getLikeNotification());
        }
        return vo;
    }

    //保存-通知设置
    @Override
    public void notificationsSettings(Settings settings) {
        Boolean pl = settings.getPinglunNotification();
        Boolean gg = settings.getGonggaoNotification();
        Boolean like = settings.getLikeNotification();
        //1.获取用户id
        Long userId = UserThreadLocal.getUserId();
        //2.调用Service查询该用户通知状态
        Settings setting = settingsApi.findByUserId(userId);

        //当用户不存在,添加新数据和用户id
        if (setting == null) {
            //封装数据
            setting = new Settings();
            setting.setGonggaoNotification(gg);
            setting.setLikeNotification(like);
            setting.setPinglunNotification(pl);
            setting.setUserId(userId);

            //添加新数据
            settingsApi.saveSettings(setting);
        } else {
            //当该用户存在原本设置,更新设置
            setting.setGonggaoNotification(gg);
            setting.setLikeNotification(like);
            setting.setPinglunNotification(pl);

            //调用api更新设置
            settingsApi.update(setting);
        }

    }
}
